<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net; style-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net; img-src 'self' data: http: https://*.myhuaweicloud.com https://*.obs.cn-north-4.myhuaweicloud.com https://*.obs.* https://*.amazonaws.com https://*.alicdn.com; font-src 'self' https://cdn.jsdelivr.net; connect-src 'self';">
    <title>文档转换知识片段工具</title>
    <!-- 引入样式库 -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/highlight.js@11.8.0/styles/github.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.0/font/bootstrap-icons.css" rel="stylesheet">
    <link rel="stylesheet" href="/static/css/style.css">
</head>
<body>
    <div class="container-fluid">
        <header class="py-3 mb-4 border-bottom bg-light">
            <div class="container d-flex align-items-center justify-content-between">
                <h1 class="fs-4">文档转换知识片段工具</h1>
                <button class="btn btn-outline-danger" id="resetAllQABtn">
                    <i class="bi bi-trash me-1"></i> 重置所有知识片段
                </button>
            </div>
        </header>

        <main class="container">
            <!-- 步骤导航 -->
            <ul class="nav nav-pills nav-fill mb-4 step-navigation">
                <li class="nav-item">
                    <a class="nav-link active" data-bs-toggle="pill" href="#step1">1. 上传文档</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" data-bs-toggle="pill" href="#step2">2. 预览与编辑</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" data-bs-toggle="pill" href="#step3">3. 生成知识片段</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" data-bs-toggle="pill" href="#step4">4. 编辑知识片段</a>
                </li>
            </ul>
            
            <!-- 隐藏的文件输入用于导入JSON -->
            <input type="file" id="importQAFile" accept=".json" style="display: none;">

            <!-- 步骤内容 -->
            <div class="tab-content">
                <!-- 步骤1：上传文档 -->
                <div class="tab-pane fade show active" id="step1">
                    <div class="card">
                        <div class="card-header">
                            <h5>上传文档</h5>
                        </div>
                        <div class="card-body">
                            <div class="upload-section">
                                <form id="uploadForm" class="mb-4">
                                    <div class="mb-3">
                                        <label for="documentFile" class="form-label">选择文件</label>
                                        <input type="file" class="form-control" id="documentFile" name="file" accept=".pdf,.doc,.docx" required>
                                    </div>
                                    
                                    <!-- 解析器选项 -->
                                    <div class="mb-3">
                                        <label for="parser_option" class="form-label">解析方式</label>
                                        <select class="form-select" id="parser_option" name="parser_option">
                                            <option value="default" data-engine="markitdown">基础解析 (仅支持移除图片)</option>
                                            <option value="advanced" data-engine="advanced">高级解析 (支持图片处理)</option>
                                            <option value="marker" data-engine="marker">Marker (支持图片处理)</option>
                                            <option value="mineru" data-engine="mineru">MinerU (支持图片处理)</option>
                                        </select>
                                    </div>
                                    
                                    <!-- 图片处理选项 -->
                                    <div class="mb-3">
                                        <label class="form-label">图片处理方式</label>
                                        <div class="form-check">
                                            <input class="form-check-input" type="radio" name="image_option" id="imageOptionObs" value="obs">
                                            <label class="form-check-label" for="imageOptionObs">
                                                保留图片并上传到OBS
                                            </label>
                                        </div>
                                        <div class="form-check">
                                            <input class="form-check-input" type="radio" name="image_option" id="imageOptionRemove" value="remove" checked>
                                            <label class="form-check-label" for="imageOptionRemove">
                                                移除所有图片
                                            </label>
                                        </div>
                                    </div>
                                    
                                    <button type="submit" class="btn btn-primary" id="uploadButton">上传</button>
                                </form>
                            </div>

                            <!-- 上传进度条 -->
                            <div id="uploadProgress" class="progress mb-3" style="display: none;">
                                <div class="progress-bar" role="progressbar" style="width: 0%"></div>
                            </div>

                            <!-- 错误消息显示区域 -->
                            <div id="uploadError" class="alert alert-danger" style="display: none;"></div>
                        </div>
                    </div>
                </div>

                <!-- 步骤2：预览与编辑 -->
                <div class="tab-pane fade" id="step2">
                    <div class="card">
                        <div class="card-header d-flex justify-content-between align-items-center">
                            <h5>Markdown 预览与编辑</h5>
                            <div>
                                <button class="btn btn-outline-secondary me-2" id="downloadMarkdownBtn">下载 Markdown</button>
                                <button class="btn btn-outline-primary me-2" id="previewMarkdownBtn">预览</button>
                                <button class="btn btn-primary" id="saveMarkdownBtn">保存</button>
                            </div>
                        </div>
                        <div class="card-body">
                            <div class="row">
                                <div class="col-md-6">
                                    <h6>编辑</h6>
                                    <textarea class="form-control markdown-editor" id="markdownEditor" rows="20"></textarea>
                                </div>
                                <div class="col-md-6">
                                    <h6>预览</h6>
                                    <div class="markdown-preview border p-3" id="markdownPreview"></div>
                                </div>
                            </div>
                            <div class="mt-3 text-end">
                                <button class="btn btn-success" id="nextToStep3">下一步：生成知识片段</button>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 步骤3：生成知识片段 -->
                <div class="tab-pane fade" id="step3">
                    <div class="card">
                        <div class="card-header">
                            <h5>生成知识片段</h5>
                        </div>
                        <div class="card-body">
                            <form id="generateQAForm">
                                <div class="mb-3">
                                    <label for="sourceName" class="form-label">知识来源</label>
                                    <input type="text" class="form-control" id="sourceName" name="source_name" placeholder="例如：公司手册、产品文档等" required>
                                </div>
                                
                                <div class="mb-3">
                                    <label for="systemName" class="form-label">系统名称</label>
                                    <input type="text" class="form-control" id="systemName" name="system_name" placeholder="例如：智能客服、知识库等" required>
                                </div>
                                
                                <div class="mb-3">
                                    <label class="form-label">生成方式</label>
                                    <div class="form-check">
                                        <input class="form-check-input" type="radio" name="generate_method" id="textSplit" value="text_split" checked>
                                        <label class="form-check-label" for="textSplit">
                                            固定文本分割
                                        </label>
                                    </div>
                                    <div class="form-check">
                                        <input class="form-check-input" type="radio" name="generate_method" id="aiQA" value="ai_qa">
                                        <label class="form-check-label" for="aiQA">
                                            AI 问答生成
                                        </label>
                                    </div>
                                </div>
                                
                                <!-- 文本分割参数 -->
                                <div id="textSplitOptions">
                                    <div class="mb-3">
                                        <label for="chunkSize" class="form-label">文本块大小（字符数）</label>
                                        <input type="number" class="form-control" id="chunkSize" name="chunk_size" value="500">
                                    </div>
                                    <div class="mb-3">
                                        <label for="overlapSize" class="form-label">重叠大小（字符数）</label>
                                        <input type="number" class="form-control" id="overlapSize" name="overlap" value="50">
                                    </div>
                                </div>
                                
                                <button type="submit" class="btn btn-primary" id="generateButton">生成知识片段</button>
                            </form>
                            <div class="mt-3" id="generateProgress" style="display: none;">
                                <div class="progress">
                                    <div class="progress-bar progress-bar-striped progress-bar-animated" role="progressbar" style="width: 100%"></div>
                                </div>
                                <p class="text-center mt-2">知识片段生成中，请稍候...</p>
                            </div>
                            <div class="alert alert-danger mt-3" id="generateError" style="display: none;"></div>
                        </div>
                    </div>
                </div>

                <!-- 步骤4：编辑知识片段 -->
                <div class="tab-pane fade" id="step4">
                    <div class="card">
                        <div class="card-header d-flex justify-content-between align-items-center">
                            <h5>知识片段预览与编辑</h5>
                            <div>
                                <button class="btn btn-outline-secondary me-2" id="importQABtn">导入 JSON</button>
                                <button class="btn btn-primary" id="downloadQABtn">下载 QA JSON</button>
                            </div>
                        </div>
                        <div class="card-body">
                            <!-- 添加新QA按钮 -->
                            <div class="mb-4 d-flex justify-content-between align-items-center">
                                <button class="btn btn-success d-flex align-items-center" id="addNewQABtn">
                                    <i class="bi bi-plus-circle me-2"></i> 新增知识片段
                                </button>
                                
                                <!-- 统计信息 -->
                                <div class="qa-stats rounded bg-light p-2 text-muted">
                                    <i class="bi bi-info-circle me-1"></i>
                                    <span id="qaStatsTotal">总数: 0</span>
                                    <span class="mx-2">|</span>
                                    <span id="qaStatsModified">已修改: 0</span>
                                </div>
                            </div>
                            
                            <!-- 添加导航控制 -->
                            <div class="navigation mb-4 d-flex justify-content-between align-items-center">
                                <div class="nav-buttons btn-group">
                                    <button class="btn btn-outline-primary" id="prevQABtn" disabled>
                                        <i class="bi bi-chevron-left"></i> 上一个
                                    </button>
                                    <button class="btn btn-outline-secondary" disabled>
                                        <span id="currentQAIndex" class="mx-2">0/0</span>
                                    </button>
                                    <button class="btn btn-outline-primary" id="nextQABtn" disabled>
                                        下一个 <i class="bi bi-chevron-right"></i>
                                    </button>
                                </div>
                                <span id="qaSaveStatus" class="badge rounded-pill"></span>
                            </div>
                            
                            <!-- QA内容区域 -->
                            <div id="qaContent" class="mb-3"></div>
                            
                            <!-- QA列表概览 - 隐藏但保留原有功能 -->
                            <div id="qaList" class="qa-list d-none">
                                <div class="text-center">
                                    <p class="text-muted">请先生成知识片段</p>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </main>

        <footer class="py-3 mt-4 border-top">
            <div class="container text-center">
                <p class="text-muted">文档转换知识片段工具 &copy; 2025</p>
            </div>
        </footer>
    </div>

    <!-- 添加图片上传隐藏表单 -->
    <input type="file" id="qaImageUpload" accept="image/*" style="display: none;">

    <!-- 引入脚本库 -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/marked@5.0.0/marked.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/highlight.js@11.8.0/lib/highlight.min.js"></script>
    <script src="/static/js/main.js"></script>
    <script>
        // 初始化marked设置，允许加载外部图片
        marked.use({
            renderer: {
                image(href, title, text) {
                    return `<img src="${href}" alt="${text}" title="${title || ''}" class="img-fluid">`;
                }
            },
            headerIds: false,
            mangle: false
        });

        document.getElementById('uploadForm').addEventListener('submit', async function(event) {
            event.preventDefault();
            const form = this;
            const fileInput = form.elements.file;
            const parserSelect = form.elements.parser_option;
            const imageOption = form.elements.image_option.value;
            
            // 检查文件是否选择
            if (!fileInput.files || !fileInput.files[0]) {
                alert('请选择要上传的文件');
                return;
            }

            const formData = new FormData();
            const file = fileInput.files[0];
            formData.append('file', file);
            formData.append('parser_option', parserSelect.value);  // 添加解析器选项
            formData.append('image_option', imageOption);  // 修正参数名为 image_option

            const uploadButton = document.getElementById('uploadButton');
            const uploadProgress = document.getElementById('uploadProgress');
            const uploadError = document.getElementById('uploadError');

            uploadButton.disabled = true;
            uploadProgress.style.display = 'block';
            uploadProgress.querySelector('.progress-bar').style.width = '0%';

            try {
                console.log('开始上传文件:', {
                    fileName: file.name,
                    parserOption: parserSelect.value,
                    imageOption: imageOption
                });

                // 上传文件
                const uploadResponse = await fetch('/api/document/upload', {
                    method: 'POST',
                    body: formData
                });

                if (!uploadResponse.ok) {
                    const error = await uploadResponse.json();
                    throw new Error(error.detail || '上传失败');
                }

                const data = await uploadResponse.json();
                console.log('上传响应:', data);
                
                if (data.error) {
                    throw new Error(data.error);
                }

                if (!data.markdown) {
                    throw new Error('未获取到文档内容');
                }

                // 更新编辑器内容
                const markdownEditor = document.getElementById('markdownEditor');
                if (markdownEditor) {
                    markdownEditor.value = data.markdown;
                    console.log('已更新编辑器内容');
                    
                    // 将初始获取的内容保存为第一次暂存内容
                    localStorage.setItem('savedMarkdownContent', data.markdown);
                    localStorage.setItem('savedMarkdownTime', new Date().toISOString());
                    console.log('已将初始内容保存为第一次暂存');
                }
                
                // 存储任务信息
                localStorage.setItem('currentTaskId', data.task_id);
                localStorage.setItem('currentFileName', data.file_name);
                
                // 显示成功信息
                uploadProgress.querySelector('.progress-bar').style.width = '100%';
                uploadError.textContent = `文件处理成功！
                    处理时间: ${data.process_time.toFixed(2)}秒
                    总耗时: ${data.total_time.toFixed(2)}秒`;
                uploadError.className = 'alert alert-success';
                uploadError.style.display = 'block';
                
                // 切换到预览与编辑步骤
                document.querySelector('.nav-link[href="#step2"]').click();
                
                // 触发预览
                document.getElementById('previewMarkdownBtn').click();
                
            } catch (error) {
                console.error('上传错误:', error);
                uploadError.textContent = error.message || '上传失败，请稍后再试';
                uploadError.className = 'alert alert-danger';
                uploadError.style.display = 'block';
            } finally {
                uploadButton.disabled = false;
                uploadProgress.style.display = 'none';
            }
        });

        // 修复预览按钮点击事件
        document.getElementById('previewMarkdownBtn').addEventListener('click', function() {
            const markdownEditor = document.getElementById('markdownEditor');
            const markdownPreview = document.getElementById('markdownPreview');
            
            if (!markdownEditor || !markdownPreview) {
                console.error('找不到编辑器或预览元素');
                return;
            }
            
            try {
                const content = markdownEditor.value;
                
                // 使用marked解析Markdown内容
                markdownPreview.innerHTML = marked.parse(content);
                
                // 输出图片诊断信息
                const images = markdownPreview.querySelectorAll('img');
                console.log(`找到 ${images.length} 张图片`);
                images.forEach((img, index) => {
                    console.log(`图片 #${index+1} 路径: ${img.src}, 是否完成加载: ${img.complete}`);
                    
                    // 添加图片加载事件处理
                    img.onerror = function() {
                        console.error('图片加载失败:', img.src);
                        this.style.border = '1px solid red';
                        this.style.padding = '5px';
                        this.setAttribute('title', '图片加载失败: ' + img.src);
                    };
                    
                    img.onload = function() {
                        console.log('图片加载成功:', img.src);
                        this.style.border = '1px solid green';
                        this.style.padding = '3px';
                        this.setAttribute('title', '图片加载成功');
                        setTimeout(() => {
                            this.style.border = '';
                            this.style.padding = '';
                        }, 1000);
                    };
                });
                
                // 代码高亮
                markdownPreview.querySelectorAll('pre code').forEach((block) => {
                    hljs.highlightBlock(block);
                });
            } catch (error) {
                console.error('预览生成失败:', error);
                markdownPreview.innerHTML = `<div class="alert alert-danger">预览生成失败: ${error.message}</div>`;
            }
        });

        // 修复图片选项更新函数
        function updateImageOptions() {
            const parserSelect = document.getElementById('parser_option');
            if (!parserSelect) {
                console.error('找不到解析器选择元素');
                return;
            }

            const selectedValue = parserSelect.value;
            const selectedEngine = parserSelect.options[parserSelect.selectedIndex].dataset.engine;
            const obsOption = document.getElementById('imageOptionObs');
            const removeOption = document.getElementById('imageOptionRemove');
            
            if (!obsOption || !removeOption) {
                console.error('找不到图片选项元素');
                return;
            }
            
            // markitdown 引擎只支持移除图片
            if (selectedValue === 'default' || selectedEngine === 'markitdown') {
                obsOption.disabled = true;
                removeOption.checked = true;
            } else {
                obsOption.disabled = false;
            }
        }
        
        // 确保在DOM加载完成后再初始化
        document.addEventListener('DOMContentLoaded', function() {
            // 初始化图片选项
            updateImageOptions();
            
            // 监听解析器选择变化
            const parserSelect = document.getElementById('parser_option');
            if (parserSelect) {
                parserSelect.addEventListener('change', updateImageOptions);
            }
            
            // 其他初始化代码...
        });

        // 修复1: 保存按钮点击事件 - 使用本地存储实现暂存功能
        document.getElementById('saveMarkdownBtn').addEventListener('click', function() {
            const markdownEditor = document.getElementById('markdownEditor');
            
            if (!markdownEditor) {
                alert('无法保存，编辑器不存在');
                return;
            }
            
            try {
                // 将编辑器内容保存到本地存储
                const content = markdownEditor.value;
                localStorage.setItem('savedMarkdownContent', content);
                localStorage.setItem('savedMarkdownTime', new Date().toISOString());
                
                // 显示保存成功提示
                alert('暂存成功！');
                
            } catch (error) {
                console.error('保存错误:', error);
                alert(`保存失败: ${error.message}`);
            }
        });

        // 下载Markdown按钮点击事件处理
        document.getElementById('downloadMarkdownBtn').addEventListener('click', function() {
            const markdownEditor = document.getElementById('markdownEditor');
            
            if (!markdownEditor || !markdownEditor.value.trim()) {
                alert('没有可下载的内容');
                return;
            }
            
            try {
                const content = markdownEditor.value;
                const fileName = localStorage.getItem('currentFileName') || 'document';
                const blob = new Blob([content], { type: 'text/markdown' });
                const downloadUrl = URL.createObjectURL(blob);
                
                const a = document.createElement('a');
                a.href = downloadUrl;
                a.download = `${fileName.split('.')[0]}.md`;
                document.body.appendChild(a);
                a.click();
                document.body.removeChild(a);
                URL.revokeObjectURL(downloadUrl);
                
                console.log('Markdown文件下载完成');
            } catch (error) {
                console.error('下载Markdown失败:', error);
                alert(`下载失败: ${error.message}`);
            }
        });

        // 添加恢复到最近一次暂存内容的功能
        document.getElementById('previewMarkdownBtn').addEventListener('click', function() {
            const markdownEditor = document.getElementById('markdownEditor');
            const markdownPreview = document.getElementById('markdownPreview');
            
            if (markdownEditor && markdownPreview) {
                const content = markdownEditor.value;
                
                // 使用marked解析Markdown内容
                markdownPreview.innerHTML = marked.parse(content);
                
                // 输出图片诊断信息
                const images = markdownPreview.querySelectorAll('img');
                console.log(`找到 ${images.length} 张图片`);
                images.forEach((img, index) => {
                    console.log(`图片 #${index+1} 路径: ${img.src}, 是否完成加载: ${img.complete}`);
                });
                
                // 确保图片能够正确加载，添加error处理
                markdownPreview.querySelectorAll('img').forEach((img) => {
                    img.onerror = function() {
                        console.error('图片加载失败:', img.src);
                        this.style.border = '1px solid red';
                        this.style.padding = '5px';
                        this.setAttribute('title', '图片加载失败: ' + img.src);
                    };
                    
                    img.onload = function() {
                        console.log('图片加载成功:', img.src);
                        this.style.border = '1px solid green';
                        this.style.padding = '3px';
                        this.setAttribute('title', '图片加载成功');
                        setTimeout(() => {
                            this.style.border = '';
                            this.style.padding = '';
                        }, 1000);
                    };
                    
                    // 对于本地图片路径，确保正确加载
                    if (img.src.startsWith('file://') || img.src.startsWith('/static/')) {
                        img.crossOrigin = 'anonymous';
                    }
                    
                    // 如果图片已经在缓存中加载完成但onload没有触发
                    if (img.complete) {
                        img.onload();
                    }
                });
                
                // 代码高亮
                markdownPreview.querySelectorAll('pre code').forEach((block) => {
                    hljs.highlightBlock(block);
                });
            }
        });

        // 添加恢复按钮功能 - 需要在HTML中添加恢复按钮
        // 在saveMarkdownBtn旁边添加恢复按钮
        const saveButton = document.getElementById('saveMarkdownBtn');
        if (saveButton && !document.getElementById('restoreMarkdownBtn')) {
            const restoreButton = document.createElement('button');
            restoreButton.id = 'restoreMarkdownBtn';
            restoreButton.className = 'btn btn-outline-secondary me-2';
            restoreButton.textContent = '恢复暂存';
            saveButton.parentNode.insertBefore(restoreButton, saveButton);
        }

        // 恢复暂存内容的事件监听
        document.addEventListener('DOMContentLoaded', function() {
            document.body.addEventListener('click', function(event) {
                if (event.target && event.target.id === 'restoreMarkdownBtn') {
                    const savedContent = localStorage.getItem('savedMarkdownContent');
                    const savedTime = localStorage.getItem('savedMarkdownTime');
                    const markdownEditor = document.getElementById('markdownEditor');
                    
                    if (savedContent && markdownEditor) {
                        if (confirm(`是否恢复到 ${new Date(savedTime).toLocaleString()} 暂存的内容？`)) {
                            markdownEditor.value = savedContent;
                            alert('已恢复到上次暂存的内容');
                        }
                    } else {
                        alert('没有找到暂存的内容');
                    }
                }
            });
        });
        
        // 修复2: 下一步按钮点击事件 - 切换到生成知识片段步骤并自动保存当前内容
        document.getElementById('nextToStep3').addEventListener('click', function() {
            // 自动暂存当前编辑器内容
            const markdownEditor = document.getElementById('markdownEditor');
            if (markdownEditor) {
                localStorage.setItem('savedMarkdownContent', markdownEditor.value);
                localStorage.setItem('savedMarkdownTime', new Date().toISOString());
            }
            
            // 切换到生成知识片段步骤
            document.querySelector('.nav-link[href="#step3"]').click();
        });
        
        // 修复3: 生成知识片段表单提交事件 - 使用本地存储的内容而不是依赖task_id
        document.getElementById('generateQAForm').addEventListener('submit', async function(event) {
            event.preventDefault(); // 阻止表单默认提交行为
            
            // 从本地存储获取Markdown内容
            const markdownContent = localStorage.getItem('savedMarkdownContent');
            if (!markdownContent) {
                alert('请先在编辑页面中保存文档内容');
                return;
            }
            
            const formData = {
                source_name: document.getElementById('sourceName').value,
                system_name: document.getElementById('systemName').value,
                generate_method: document.querySelector('input[name="generate_method"]:checked').value,
                chunk_size: parseInt(document.getElementById('chunkSize').value, 10),
                overlap: parseInt(document.getElementById('overlapSize').value, 10),
                markdown_content: markdownContent  // 直接将Markdown内容作为参数传递
            };
            
            const generateButton = document.getElementById('generateButton');
            const generateProgress = document.getElementById('generateProgress');
            const generateError = document.getElementById('generateError');
            
            try {
                generateButton.disabled = true;
                generateProgress.style.display = 'block';
                generateError.style.display = 'none';
                
                console.log('开始生成知识片段:', formData);
                
                // 调用生成知识片段API
                const response = await fetch('/api/qa/generate', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify(formData)
                });
                
                if (!response.ok) {
                    const error = await response.json();
                    throw new Error(error.detail || '生成失败');
                }
                
                const data = await response.json();
                console.log('生成响应:', data);
                
                // 将生成的知识片段保存到本地存储
                localStorage.setItem('generatedQAPairs', JSON.stringify(data.qa_pairs));
                
                // 初始化知识片段编辑系统
                initQAEditor(data.qa_pairs);
                
                // 存储QA任务ID
                localStorage.setItem('currentQATaskId', data.task_id);
                
                // 切换到知识片段编辑步骤
                document.querySelector('.nav-link[href="#step4"]').click();
                
            } catch (error) {
                console.error('生成错误:', error);
                generateError.textContent = error.message || '生成失败，请稍后再试';
                generateError.style.display = 'block';
            } finally {
                generateButton.disabled = false;
                generateProgress.style.display = 'none';
            }
        });
        
        // 新增：知识片段编辑系统相关变量和函数
        let currentQAPairs = null;
        let currentQAIndex = 0;
        let modifiedQAPairs = new Set(); // 记录已修改的QA对索引
        let deletedQAPairs = new Set(); // 记录已删除的QA对索引
        
        // 初始化知识片段编辑系统
        function initQAEditor(qaPairs) {
            if (!qaPairs || !Array.isArray(qaPairs) || qaPairs.length === 0) {
                document.getElementById('qaContent').innerHTML = '<div class="alert alert-warning">未找到知识片段数据</div>';
                
                // 重置统计
                document.getElementById('qaStatsTotal').innerHTML = '总数: <strong>0</strong> 条';
                document.getElementById('qaStatsModified').innerHTML = '已修改: <strong>0</strong> 条 | 已删除: <strong>0</strong> 条';
                return;
            }
            
            currentQAPairs = qaPairs;
            currentQAIndex = 0;
            modifiedQAPairs.clear();
            deletedQAPairs.clear();
            
            updateQANavigation();
            displayCurrentQA();
            
            // 更新统计信息
            updateQAStats();
            
            // 也显示在原来的列表中（隐藏但功能保留）
            displayQAPairs(qaPairs);
        }
        
        // 更新QA导航状态
        function updateQANavigation() {
            if (!currentQAPairs) return;
            
            const total = currentQAPairs.length;
            document.getElementById('currentQAIndex').textContent = `${currentQAIndex + 1}/${total}`;
            document.getElementById('prevQABtn').disabled = currentQAIndex === 0;
            document.getElementById('nextQABtn').disabled = currentQAIndex === total - 1 || total === 0;
            
            // 如果有修改，在底部显示保存提示
            if (modifiedQAPairs.size > 0 || deletedQAPairs.size > 0) {
                document.getElementById('downloadQABtn').classList.add('btn-success');
                document.getElementById('downloadQABtn').innerHTML = '下载修改后的 QA JSON';
            } else {
                document.getElementById('downloadQABtn').classList.remove('btn-success');
                document.getElementById('downloadQABtn').innerHTML = '下载 QA JSON';
            }
        }
        
        // 显示当前QA对
        function displayCurrentQA() {
            if (!currentQAPairs || currentQAPairs.length === 0) return;
            
            const pair = currentQAPairs[currentQAIndex];
            const qaContent = document.getElementById('qaContent');
            const isDeleted = deletedQAPairs.has(currentQAIndex);
            
            qaContent.innerHTML = `
                <div class="qa-item card ${isDeleted ? 'border-danger bg-light opacity-75' : 'border-primary'}">
                    <div class="card-header ${isDeleted ? 'bg-danger bg-opacity-10' : 'bg-primary bg-opacity-10'} d-flex justify-content-between align-items-center">
                        <h6 class="mb-0 d-flex align-items-center">
                            <i class="bi ${isDeleted ? 'bi-trash' : 'bi-chat-dots'} me-2"></i>
                            知识片段 #${currentQAIndex + 1}
                        </h6>
                        <div>
                            ${isDeleted ? 
                              '<span class="badge bg-danger me-2">已标记删除</span><button class="btn btn-sm btn-success d-flex align-items-center restore-qa-btn"><i class="bi bi-arrow-counterclockwise me-1"></i> 恢复</button>' : 
                              '<button class="btn btn-sm btn-outline-danger d-flex align-items-center delete-qa-btn"><i class="bi bi-trash me-1"></i> 删除</button>'}
                        </div>
                    </div>
                    <div class="card-body">
                        <div class="mb-3">
                            <label class="form-label d-flex align-items-center">
                                <i class="bi bi-question-circle me-2 text-primary"></i>
                                <strong>问题</strong>
                            </label>
                            <textarea class="form-control qa-question ${isDeleted ? 'bg-light' : ''}" rows="2" ${isDeleted ? 'disabled' : ''}>${pair.Q || ''}</textarea>
                        </div>
                        <div class="mb-3">
                            <label class="form-label d-flex align-items-center">
                                <i class="bi bi-chat-square-text me-2 text-primary"></i>
                                <strong>答案</strong>
                            </label>
                            <div class="input-group mb-2">
                                <textarea class="form-control qa-answer ${isDeleted ? 'bg-light' : ''}" rows="4" ${isDeleted ? 'disabled' : ''}>${pair.A || ''}</textarea>
                                ${!isDeleted ? `
                                <!-- 添加图片上传按钮 -->
                                <div class="input-group-append">
                                    <button class="btn btn-outline-primary upload-image-btn" type="button">
                                        <i class="bi bi-image"></i> 插入图片
                                    </button>
                                </div>` : ''}
                            </div>
                        </div>
                        ${!isDeleted ? `
                        <div class="mb-3">
                            <div class="d-flex justify-content-between align-items-center mb-2">
                                <label class="form-label mb-0 d-flex align-items-center">
                                    <i class="bi bi-eye me-2 text-primary"></i>
                                    <strong>答案预览</strong>
                                </label>
                                <button class="btn btn-sm btn-outline-primary preview-qa-btn d-flex align-items-center">
                                    <i class="bi bi-arrow-clockwise me-1"></i> 刷新预览
                                </button>
                            </div>
                            <div class="markdown-preview border p-3 rounded" id="qaMarkdownPreview"></div>
                        </div>
                        <div class="d-flex justify-content-end">
                            <button class="btn btn-primary save-qa-btn d-flex align-items-center">
                                <i class="bi bi-save me-2"></i> 保存修改
                            </button>
                        </div>
                        ` : ''}
                    </div>
                </div>
            `;
            
            // 绑定按钮事件
            if (!isDeleted) {
                qaContent.querySelector('.preview-qa-btn').addEventListener('click', previewQAMarkdown);
                qaContent.querySelector('.save-qa-btn').addEventListener('click', saveQAChanges);
                qaContent.querySelector('.delete-qa-btn').addEventListener('click', deleteQAPair);
                
                // 自动触发一次预览
                previewQAMarkdown();
            } else {
                qaContent.querySelector('.restore-qa-btn').addEventListener('click', restoreQAPair);
            }
            
            updateQASaveStatus();
        }
        
        // 预览QA中的Markdown
        function previewQAMarkdown() {
            const answerTextarea = document.querySelector('.qa-answer');
            if (!answerTextarea) return;
            
            const answerText = answerTextarea.value;
            const preview = document.getElementById('qaMarkdownPreview');
            
            if (preview) {
                // 使用marked解析Markdown内容
                preview.innerHTML = marked.parse(answerText);
                
                // 输出图片诊断信息
                const images = preview.querySelectorAll('img');
                console.log(`找到 ${images.length} 张图片`);
                images.forEach((img, index) => {
                    console.log(`图片 #${index+1} 路径: ${img.src}, 是否完成加载: ${img.complete}`);
                });
                
                // 确保图片能够正确加载，添加error处理
                preview.querySelectorAll('img').forEach((img) => {
                    img.onerror = function() {
                        console.error('图片加载失败:', img.src);
                        this.style.border = '1px solid red';
                        this.style.padding = '5px';
                        this.setAttribute('title', '图片加载失败: ' + img.src);
                    };
                    
                    img.onload = function() {
                        console.log('图片加载成功:', img.src);
                        this.style.border = '1px solid green';
                        this.style.padding = '3px';
                        this.setAttribute('title', '图片加载成功');
                        setTimeout(() => {
                            this.style.border = '';
                            this.style.padding = '';
                        }, 1000);
                    };
                    
                    // 对于本地图片路径，确保正确加载
                    if (img.src.startsWith('file://') || img.src.startsWith('/static/')) {
                        img.crossOrigin = 'anonymous';
                    }
                    
                    // 如果图片已经在缓存中加载完成但onload没有触发
                    if (img.complete) {
                        img.onload();
                    }
                });
                
                // 代码高亮
                preview.querySelectorAll('pre code').forEach((block) => {
                    hljs.highlightBlock(block);
                });
            }
        }
        
        // 保存QA更改
        function saveQAChanges() {
            if (!currentQAPairs) return;
            
            const questionTextarea = document.querySelector('.qa-question');
            const answerTextarea = document.querySelector('.qa-answer');
            
            if (!questionTextarea || !answerTextarea) return;
            
            // 获取新的问题和答案
            const newQuestion = questionTextarea.value.trim();
            const newAnswer = answerTextarea.value.trim();
            
            // 检查是否有实际修改
            const currentPair = currentQAPairs[currentQAIndex];
            const hasChanged = currentPair.Q !== newQuestion || currentPair.A !== newAnswer;
            
            if (!hasChanged) {
                // 如果没有变化，显示提示并返回
                const saveStatus = document.getElementById('qaSaveStatus');
                saveStatus.textContent = '未检测到变化';
                saveStatus.className = 'badge rounded-pill bg-info';
                setTimeout(() => {
                    saveStatus.textContent = '';
                    saveStatus.className = 'badge rounded-pill';
                }, 2000);
                return;
            }
            
            // 更新数据
            currentQAPairs[currentQAIndex].Q = newQuestion;
            currentQAPairs[currentQAIndex].A = newAnswer;
            
            // 标记为已修改
            modifiedQAPairs.add(currentQAIndex);
            
            // 更新状态
            updateQASaveStatus();
            updateQANavigation();
            
            // 更新本地存储
            localStorage.setItem('generatedQAPairs', JSON.stringify(currentQAPairs));
            
            // 显示成功消息
            const saveStatus = document.getElementById('qaSaveStatus');
            saveStatus.textContent = '修改已保存';
            saveStatus.className = 'badge rounded-pill bg-success';
            setTimeout(() => {
                saveStatus.textContent = '';
                saveStatus.className = 'badge rounded-pill';
            }, 2000);
        }
        
        // 删除QA对
        function deleteQAPair() {
            if (!currentQAPairs) return;
            
            if (confirm('确定要删除此知识片段吗？')) {
                deletedQAPairs.add(currentQAIndex);
                updateQASaveStatus();
                updateQANavigation();
                displayCurrentQA();
            }
        }
        
        // 恢复删除的QA对
        function restoreQAPair() {
            if (!currentQAPairs) return;
            
            deletedQAPairs.delete(currentQAIndex);
            updateQASaveStatus();
            updateQANavigation();
            displayCurrentQA();
        }
        
        // 更新QA保存状态
        function updateQASaveStatus() {
            const saveStatus = document.getElementById('qaSaveStatus');
            
            if (deletedQAPairs.has(currentQAIndex)) {
                saveStatus.textContent = '已标记删除';
                saveStatus.className = 'badge rounded-pill bg-danger';
            } else if (modifiedQAPairs.has(currentQAIndex)) {
                saveStatus.textContent = '已修改';
                saveStatus.className = 'badge rounded-pill bg-warning text-dark';
            } else {
                saveStatus.textContent = '';
                saveStatus.className = 'badge rounded-pill';
            }
            
            // 更新统计信息
            updateQAStats();
        }
        
        // 更新QA统计信息
        function updateQAStats() {
            if (!currentQAPairs) return;
            
            const totalStats = document.getElementById('qaStatsTotal');
            const modifiedStats = document.getElementById('qaStatsModified');
            
            const total = currentQAPairs.length;
            const modified = modifiedQAPairs.size;
            const deleted = deletedQAPairs.size;
            
            totalStats.innerHTML = `总数: <strong>${total}</strong> 条`;
            modifiedStats.innerHTML = `已修改: <strong>${modified}</strong> 条 | 已删除: <strong>${deleted}</strong> 条`;
            
            if (modified > 0 || deleted > 0) {
                document.getElementById('downloadQABtn').classList.add('btn-success');
                document.getElementById('downloadQABtn').innerHTML = '<i class="bi bi-download me-1"></i> 下载修改后的 QA';
            } else {
                document.getElementById('downloadQABtn').classList.remove('btn-success');
                document.getElementById('downloadQABtn').innerHTML = '<i class="bi bi-download me-1"></i> 下载 QA';
            }
        }
        
        // 绑定导航按钮事件
        document.getElementById('prevQABtn').addEventListener('click', function() {
            if (currentQAIndex > 0) {
                currentQAIndex--;
                displayCurrentQA();
                updateQANavigation();
            }
        });
        
        document.getElementById('nextQABtn').addEventListener('click', function() {
            if (currentQAPairs && currentQAIndex < currentQAPairs.length - 1) {
                currentQAIndex++;
                displayCurrentQA();
                updateQANavigation();
            }
        });
        
        // 添加显示知识片段的函数 (原函数保留但优化)
        function displayQAPairs(qaPairs) {
            const qaList = document.getElementById('qaList');
            
            if (!qaPairs || qaPairs.length === 0) {
                qaList.innerHTML = '<div class="text-center"><p class="text-muted">未生成知识片段或生成结果为空</p></div>';
                return;
            }
            
            // 清空现有内容
            qaList.innerHTML = '';
            
            // 添加每个QA对
            qaPairs.forEach((qa, index) => {
                const qaItem = document.createElement('div');
                qaItem.className = 'qa-item card mb-3';
                qaItem.innerHTML = `
                    <div class="card-header bg-light d-flex justify-content-between align-items-center">
                        <h6 class="mb-0">知识片段 #${index + 1}</h6>
                        <div>
                            <button class="btn btn-sm btn-outline-primary edit-qa-btn">编辑</button>
                            <button class="btn btn-sm btn-outline-danger delete-qa-btn">删除</button>
                        </div>
                    </div>
                    <div class="card-body">
                        <div class="mb-3">
                            <label class="form-label">问题</label>
                            <textarea class="form-control qa-question" rows="2">${qa.Q || ''}</textarea>
                        </div>
                        <div>
                            <label class="form-label">答案</label>
                            <textarea class="form-control qa-answer" rows="4">${qa.A || ''}</textarea>
                        </div>
                    </div>
                `;
                
                qaList.appendChild(qaItem);
            });
        }
        
        // 修改下载知识片段JSON文件功能，支持下载修改后的内容
        document.getElementById('downloadQABtn').addEventListener('click', function() {
            if (!currentQAPairs || currentQAPairs.length === 0) {
                alert('没有可下载的知识片段');
                return;
            }
            
            // 获取来源和系统名称
            const sourceName = localStorage.getItem('sourceName') || document.getElementById('sourceName').value || '未知来源';
            const systemName = localStorage.getItem('systemName') || document.getElementById('systemName').value || '未知系统';
            
            // 创建新的QA对数组，排除已删除的条目
            const finalQaPairs = currentQAPairs.filter((_, index) => !deletedQAPairs.has(index));
            
            // 创建最终的JSON对象
            const finalData = {
                task_id: localStorage.getItem('currentQATaskId'),
                source_name: sourceName,
                system_name: systemName,
                qa_pairs: finalQaPairs,
                created_at: new Date().toISOString()
            };
            
            const blob = new Blob([JSON.stringify(finalData, null, 2)], { type: 'application/json' });
            const downloadUrl = URL.createObjectURL(blob);
            
            const a = document.createElement('a');
            a.href = downloadUrl;
            a.download = `qa_result_${new Date().toISOString().slice(0,10)}.json`;
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
            URL.revokeObjectURL(downloadUrl);
            
            alert('文件已下载');
        });
        
        // 导入JSON按钮点击事件
        document.getElementById('importQABtn').addEventListener('click', function() {
            // 更新按钮显示
            this.innerHTML = '<i class="bi bi-upload me-1"></i> 导入 JSON';
            
            // 触发隐藏的文件输入框的点击事件
            document.getElementById('importQAFile').click();
        });
        
        // 监听文件选择变化
        document.getElementById('importQAFile').addEventListener('change', async function(event) {
            const file = event.target.files[0];
            if (!file) return;
            
            // 更新按钮显示
            const importBtn = document.getElementById('importQABtn');
            importBtn.innerHTML = '<i class="bi bi-hourglass-split me-1"></i> 正在导入...';
            importBtn.disabled = true;
            
            try {
                // 读取选择的JSON文件
                const fileReader = new FileReader();
                
                fileReader.onload = function(e) {
                    try {
                        const jsonData = JSON.parse(e.target.result);
                        
                        // 检查数据格式是否正确（是否有qa_pairs字段）
                        if (!jsonData.qa_pairs || !Array.isArray(jsonData.qa_pairs)) {
                            throw new Error('无效的JSON格式，缺少qa_pairs数组字段');
                        }
                        
                        // 转换字段名
                        const convertedQAPairs = jsonData.qa_pairs.map(pair => ({
                            Q: pair.question || pair.Q,
                            A: pair.answer || pair.A
                        }));
                        
                        // 导入数据
                        currentQAPairs = convertedQAPairs;
                        localStorage.setItem('generatedQAPairs', JSON.stringify(currentQAPairs));
                        
                        // 如果JSON包含来源和系统信息，也更新表单和本地存储
                        if (jsonData.source_name) {
                            document.getElementById('sourceName').value = jsonData.source_name;
                            localStorage.setItem('sourceName', jsonData.source_name);
                        }
                        
                        if (jsonData.system_name) {
                            document.getElementById('systemName').value = jsonData.system_name;
                            localStorage.setItem('systemName', jsonData.system_name);
                        }
                        
                        // 保存任务ID如果有的话
                        if (jsonData.task_id) {
                            localStorage.setItem('currentQATaskId', jsonData.task_id);
                        }
                        
                        // 重置编辑状态
                        currentQAIndex = 0;
                        modifiedQAPairs.clear();
                        deletedQAPairs.clear();
                        
                        // 更新界面
                        initQAEditor(currentQAPairs);
                        
                        importBtn.innerHTML = '<i class="bi bi-check-circle me-1"></i> 导入成功';
                        setTimeout(() => {
                            importBtn.innerHTML = '<i class="bi bi-upload me-1"></i> 导入 JSON';
                            importBtn.disabled = false;
                        }, 2000);
                        
                        alert(`成功导入 ${currentQAPairs.length} 个知识片段`);
                    } catch (parseError) {
                        console.error('解析JSON文件失败:', parseError);
                        alert(`解析JSON文件失败: ${parseError.message}`);
                        importBtn.innerHTML = '<i class="bi bi-exclamation-triangle me-1"></i> 导入失败';
                        setTimeout(() => {
                            importBtn.innerHTML = '<i class="bi bi-upload me-1"></i> 导入 JSON';
                            importBtn.disabled = false;
                        }, 2000);
                    }
                };
                
                fileReader.onerror = function() {
                    alert('读取文件失败');
                    importBtn.innerHTML = '<i class="bi bi-exclamation-triangle me-1"></i> 导入失败';
                    setTimeout(() => {
                        importBtn.innerHTML = '<i class="bi bi-upload me-1"></i> 导入 JSON';
                        importBtn.disabled = false;
                    }, 2000);
                };
                
                fileReader.readAsText(file);
                
                // 清空文件输入，以便再次选择同一文件时触发change事件
                this.value = '';
            } catch (error) {
                console.error('导入JSON文件失败:', error);
                alert(`导入失败: ${error.message}`);
                importBtn.innerHTML = '<i class="bi bi-exclamation-triangle me-1"></i> 导入失败';
                setTimeout(() => {
                    importBtn.innerHTML = '<i class="bi bi-upload me-1"></i> 导入 JSON';
                    importBtn.disabled = false;
                }, 2000);
                this.value = '';
            }
        });
        
        // 检查本地存储中是否有之前生成的知识片段，如果有则加载
        document.addEventListener('DOMContentLoaded', function() {
            try {
                const savedQAPairs = localStorage.getItem('generatedQAPairs');
                if (savedQAPairs) {
                    const qaPairs = JSON.parse(savedQAPairs);
                    if (qaPairs && Array.isArray(qaPairs) && qaPairs.length > 0) {
                        console.log('从本地存储加载知识片段数据:', qaPairs.length);
                        initQAEditor(qaPairs);
                    }
                }
            } catch (error) {
                console.error('加载本地存储的知识片段数据失败:', error);
            }
        });

        // 添加图片上传功能的事件处理
        document.body.addEventListener('click', function(event) {
            // 使用事件委托来处理上传图片按钮点击
            if (event.target.closest('.upload-image-btn')) {
                // 触发文件选择框
                document.getElementById('qaImageUpload').click();
            }
        });
        
        // 处理图片文件选择
        document.getElementById('qaImageUpload').addEventListener('change', async function(event) {
            if (!this.files || !this.files[0]) return;
            
            const file = this.files[0];
            const formData = new FormData();
            formData.append('file', file);
            
            try {
                // 获取答案文本框和上传按钮
                const answerTextarea = document.querySelector('.qa-answer');
                const uploadBtn = document.querySelector('.upload-image-btn');
                const cursorPosition = answerTextarea.selectionStart;
                
                // 在光标位置插入上传中提示
                const uploadingText = ' [图片上传中...] ';
                const originalValue = answerTextarea.value;
                answerTextarea.value = originalValue.substring(0, cursorPosition) + 
                                       uploadingText + 
                                       originalValue.substring(cursorPosition);
                
                // 更新按钮状态
                const originalBtnHtml = uploadBtn.innerHTML;
                uploadBtn.innerHTML = '<i class="bi bi-arrow-repeat spin me-1"></i> 上传中...';
                uploadBtn.disabled = true;
                
                // 发送上传请求
                const response = await fetch('/api/qa/upload-image', {
                    method: 'POST',
                    body: formData
                });
                
                if (!response.ok) {
                    throw new Error('图片上传失败');
                }
                
                const result = await response.json();
                
                // 替换上传中提示为Markdown图片链接
                answerTextarea.value = answerTextarea.value.replace(
                    uploadingText, 
                    result.markdown
                );
                
                // 更新按钮状态
                uploadBtn.innerHTML = '<i class="bi bi-check-circle me-1"></i> 已上传';
                setTimeout(() => {
                    uploadBtn.innerHTML = originalBtnHtml;
                    uploadBtn.disabled = false;
                }, 1500);
                
                // 刷新预览
                previewQAMarkdown();
                
                // 更新预览并高亮新插入的图片
                const preview = document.getElementById('qaMarkdownPreview');
                const newImg = preview.querySelector(`img[src="${result.url}"]`);
                if (newImg) {
                    newImg.classList.add('highlight-new');
                    setTimeout(() => {
                        newImg.classList.remove('highlight-new');
                    }, 3000);
                }
                
            } catch (error) {
                console.error('上传图片失败:', error);
                alert(`上传图片失败: ${error.message}`);
                
                // 恢复按钮状态
                const uploadBtn = document.querySelector('.upload-image-btn');
                uploadBtn.innerHTML = '<i class="bi bi-image"></i> 插入图片';
                uploadBtn.disabled = false;
                
                // 移除上传中提示
                const answerTextarea = document.querySelector('.qa-answer');
                answerTextarea.value = answerTextarea.value.replace(' [图片上传中...] ', '');
            }
            
            // 重置文件输入，以便可以再次选择同一文件
            this.value = '';
        });
        
        // 添加新建QA条目功能
        document.getElementById('addNewQABtn').addEventListener('click', async function() {
            // 更新按钮状态
            const addBtn = this;
            const originalText = addBtn.innerHTML;
            addBtn.innerHTML = '<i class="bi bi-hourglass-split me-2"></i> 创建中...';
            addBtn.disabled = true;
            
            try {
                // 调用API创建新的QA条目
                const response = await fetch('/api/qa/new-qa-entry', {
                    method: 'POST'
                });
                
                if (!response.ok) {
                    throw new Error('创建新知识片段失败');
                }
                
                const newQA = await response.json();
                
                // 确保新QA的格式正确
                const formattedQA = {
                    Q: newQA.Q || newQA.question || '',
                    A: newQA.A || newQA.answer || ''
                };
                
                // 如果currentQAPairs尚未初始化，则初始化
                if (!currentQAPairs) {
                    currentQAPairs = [];
                }
                
                // 在当前位置的下一个位置插入新QA
                const insertIndex = currentQAIndex + 1;
                currentQAPairs.splice(insertIndex, 0, formattedQA);
                
                // 更新本地存储
                localStorage.setItem('generatedQAPairs', JSON.stringify(currentQAPairs));
                
                // 跳转到新添加的QA
                currentQAIndex = insertIndex;
                
                // 更新导航和显示
                updateQANavigation();
                displayCurrentQA();
                
                // 显示成功状态
                addBtn.innerHTML = '<i class="bi bi-check-circle me-2"></i> 创建成功';
                setTimeout(() => {
                    addBtn.innerHTML = originalText;
                    addBtn.disabled = false;
                }, 1500);
                
            } catch (error) {
                console.error('创建新知识片段失败:', error);
                alert(`创建失败: ${error.message}`);
                
                // 恢复按钮状态
                addBtn.innerHTML = originalText;
                addBtn.disabled = false;
            }
        });

        // 添加重置所有知识片段的功能
        document.getElementById('resetAllQABtn').addEventListener('click', function() {
            // 创建模态框HTML
            const modalHtml = `
                <div class="modal fade" id="resetConfirmModal" tabindex="-1" aria-labelledby="resetConfirmModalLabel" aria-hidden="true">
                    <div class="modal-dialog">
                        <div class="modal-content">
                            <div class="modal-header">
                                <h5 class="modal-title text-danger" id="resetConfirmModalLabel">
                                    <i class="bi bi-exclamation-triangle-fill me-2"></i>
                                    警告：重置所有知识片段
                                </h5>
                                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                            </div>
                            <div class="modal-body">
                                <p class="text-danger">
                                    <strong>此操作将清空所有知识片段数据，且不可恢复！</strong>
                                </p>
                                <p>请确认是否继续？</p>
                                <div class="form-check">
                                    <input class="form-check-input" type="checkbox" id="confirmReset">
                                    <label class="form-check-label" for="confirmReset">
                                        我确认要清空所有知识片段
                                    </label>
                                </div>
                            </div>
                            <div class="modal-footer">
                                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                                <button type="button" class="btn btn-danger" id="confirmResetBtn" disabled>
                                    <i class="bi bi-trash me-1"></i> 确认重置
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            `;
            
            // 将模态框添加到body
            const modalElement = document.createElement('div');
            modalElement.innerHTML = modalHtml;
            document.body.appendChild(modalElement);
            
            // 初始化模态框
            const resetModal = new bootstrap.Modal(document.getElementById('resetConfirmModal'));
            
            // 监听确认复选框
            const confirmCheckbox = document.getElementById('confirmReset');
            const confirmButton = document.getElementById('confirmResetBtn');
            
            confirmCheckbox.addEventListener('change', function() {
                confirmButton.disabled = !this.checked;
            });
            
            // 监听确认按钮点击
            confirmButton.addEventListener('click', function() {
                // 清空本地存储中的知识片段数据
                localStorage.removeItem('generatedQAPairs');
                localStorage.removeItem('currentQATaskId');
                
                // 重置当前状态，并创建一个空白的 QA 对象
                currentQAPairs = [{
                    Q: '',
                    A: ''
                }];
                currentQAIndex = 0;
                modifiedQAPairs.clear();
                deletedQAPairs.clear();
                
                // 更新界面
                initQAEditor(currentQAPairs);
                
                // 更新统计信息
                document.getElementById('qaStatsTotal').innerHTML = '总数: <strong>1</strong> 条';
                document.getElementById('qaStatsModified').innerHTML = '已修改: <strong>0</strong> 条 | 已删除: <strong>0</strong> 条';
                
                // 更新导航状态
                document.getElementById('currentQAIndex').textContent = '1/1';
                document.getElementById('prevQABtn').disabled = true;
                document.getElementById('nextQABtn').disabled = true;
                
                // 更新下载按钮状态
                document.getElementById('downloadQABtn').classList.remove('btn-success');
                document.getElementById('downloadQABtn').innerHTML = '<i class="bi bi-download me-1"></i> 下载 QA';
                
                // 关闭模态框
                resetModal.hide();
                
                // 显示成功提示
                const toastHtml = `
                    <div class="toast align-items-center text-white bg-success border-0 position-fixed top-0 end-0 m-3" role="alert" aria-live="assertive" aria-atomic="true">
                        <div class="d-flex">
                            <div class="toast-body">
                                <i class="bi bi-check-circle me-2"></i>
                                已重置并创建空白知识片段
                            </div>
                            <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast" aria-label="Close"></button>
                        </div>
                    </div>
                `;
                
                const toastElement = document.createElement('div');
                toastElement.innerHTML = toastHtml;
                document.body.appendChild(toastElement);
                
                const toast = new bootstrap.Toast(toastElement.querySelector('.toast'));
                toast.show();
                
                // 3秒后自动移除提示
                setTimeout(() => {
                    toastElement.remove();
                }, 3000);
            });
            
            // 显示模态框
            resetModal.show();
            
            // 模态框关闭时清理
            document.getElementById('resetConfirmModal').addEventListener('hidden.bs.modal', function() {
                modalElement.remove();
            });
        });
    </script>
</body>
</html> 